package pers.dzk.fivelnarow.window;

import pers.dzk.fivelnarow.checkerboard.Checkerboard;
import pers.dzk.fivelnarow.checkerboard.CheckerboardSuper;
import pers.dzk.fivelnarow.config.CheckerboardConfig;
import pers.dzk.fivelnarow.config.PieceConfig;
import pers.dzk.fivelnarow.config.StartWindowConfig;
import pers.dzk.fivelnarow.config.util.PieceSkinResult;
import pers.dzk.fivelnarow.config.util.ResourcesPath;
import pers.dzk.fivelnarow.ending.Ending;
import pers.dzk.fivelnarow.ending.IEnding;
import pers.dzk.fivelnarow.judge.Judge;
import pers.dzk.fivelnarow.judge.JudgeSuper;
import pers.dzk.fivelnarow.piece.BlackPiece;
import pers.dzk.fivelnarow.piece.Piece;
import pers.dzk.fivelnarow.piece.WhitePiece;
import pers.dzk.fivelnarow.player.computer.AlphaV1;
import pers.dzk.fivelnarow.player.people.PeopleOne;
import pers.dzk.fivelnarow.player.people.PeoplePlayer;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;
import java.util.List;

/**
 * 游戏启动界面
 * @author 丁泽凯
 */
public class StartWindow extends JFrame {
    private JPanel panel = (JPanel) this.getContentPane();
    private Font font_title = new Font("",Font.BOLD,35);
    private Font font_button = new Font("",Font.BOLD,26);
    private Font font_label = new Font("",Font.HANGING_BASELINE,22);
    private Font font_textField = new Font("",Font.TRUETYPE_FONT,18);
    private Font font_comboBox = new Font("",Font.TRUETYPE_FONT,18);
    private JLabel label_title = new JLabel("五 子 棋 项 目");
    private JLabel label_mode = new JLabel("游戏模式");
    private JComboBox<String> comboBox_mode = new JComboBox();
    private JLabel label_pieceSkin = new JLabel("棋子皮肤");
    private JComboBox<String> comboBox_pieceSkin = new JComboBox();
    private JLabel label_checkerboardSkin = new JLabel("棋盘皮肤");
    private JComboBox<String> comboBox_checkerboardSkin = new JComboBox();
    private JLabel label_pieceCount = new JLabel("棋子数量");
    private TextField textField_pieceCount = new TextField("50",4);
    private JButton button_start = new JButton("启 动");
    private final String gameMod_pc = "人机对战";
    private final String gameMod_cc = "机器人对战";
    private final String gameMod_pp = "双人对战";
    private final String gameMod_pps = "局域网对战";

    //修改窗体UI
    static {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void frameInitial(){
        Image icon = Toolkit.getDefaultToolkit().getImage(ResourcesPath.IMG_PATH+"/startWindow/logo.jpg");
        setIconImage(icon);
        setTitle("五子棋启动器");
        setSize(StartWindowConfig.getWidth(), StartWindowConfig.getHeight());
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(3);
    }
    private void panelInitial(){
        String path = ResourcesPath.IMG_PATH+"/startWindow/tx.jpg";
        ImageIcon background = new ImageIcon(path);
        background.setImage(background.getImage().getScaledInstance(getWidth(),getHeight(), Image.SCALE_DEFAULT));
        JLabel label = new JLabel(background);
        label.setBounds(0, 0, this.getWidth(), this.getHeight());
        panel.setOpaque(false);
        this.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
        panel.setLayout(null);
        panel.add(label_title);
        panel.add(label_mode);
        panel.add(comboBox_mode);
        panel.add(label_pieceSkin);
        panel.add(comboBox_pieceSkin);
        panel.add(label_checkerboardSkin);
        panel.add(comboBox_checkerboardSkin);
        panel.add(label_pieceCount);
        panel.add(textField_pieceCount);
        panel.add(button_start);
        panel.setBackground(Color.lightGray);
        panel.setBackground(Color.lightGray);
        panel.setBackground(Color.lightGray);
        panel.setBackground(Color.lightGray);
        panel.setBackground(Color.lightGray);
    }
    private void labelInitial(){
        label_title.setBounds(250,0,400,100);
        label_title.setFont(font_title);
        label_mode.setBounds(50,0+100,100,100);
        label_mode.setFont(font_label);
        label_pieceSkin.setBounds(50,0+100+50,100,100);
        label_pieceSkin.setFont(font_label);
        label_checkerboardSkin.setBounds(50,0+100+50+50,100,100);
        label_checkerboardSkin.setFont(font_label);
        label_pieceCount.setBounds(50,0+100+50+50+50,100,100);
        label_pieceCount.setFont(font_label);
    }
    private void buttonInitial(){
        button_start.setBounds(630,400,150,55);
        button_start.setFont(font_button);
        button_start.setBackground(new Color(192,192,92));
        button_start.addActionListener(e -> {
            System.out.println("#################### Play initialization info ####################");
            int pc = Integer.parseInt(textField_pieceCount.getText());
            String mod = comboBox_mode.getSelectedItem().toString();
            String ps = comboBox_pieceSkin.getSelectedItem().toString();
            String cs = comboBox_checkerboardSkin.getSelectedItem().toString();
            ImageIcon img = CheckerboardConfig.getSkin(cs);
//            //随机先后手，黑棋白棋
//            boolean order = new Random().nextBoolean();
//            boolean type = new Random().nextBoolean();
            //随机先后手，黑棋白棋
            boolean order = false;
            boolean type = false;
            //创建2位玩家的棋子集合
            List<Piece> pieces = new ArrayList();
            List<Piece> pieces2 = new ArrayList();
            PieceSkinResult psr = PieceConfig.getSkin(ps);
            for (int i = 0; i < pc; i++) {
                BlackPiece bp;
                WhitePiece wp;
                if(psr == null){
                    bp = new BlackPiece();
                    wp = new WhitePiece();
                }else {
                    bp = new BlackPiece(psr.getBlack().getImg(),psr.getBlack().getOffset());
                    wp = new WhitePiece(psr.getWhite().getImg(), psr.getWhite().getOffset());
                }
                if(type){
                    pieces.add(bp);
                    pieces2.add(wp);
                }else{
                    pieces.add(wp);
                    pieces2.add(bp);
                }
            }
            //判断选择的模式是否等于注解的name值
            //noinspection AlibabaUndefineMagicConstant
            if(mod == gameMod_pc){
                setVisible(false);
                new MainWindow(new Checkerboard(img),new PeopleOne(pieces,order),new AlphaV1(pieces2,!order),new Judge(),new Ending());
            }else            //noinspection AlibabaUndefineMagicConstant
                if(mod == gameMod_cc){
                    setVisible(false);
                new MainWindow(new Checkerboard(img),new AlphaV1(pieces,order),new AlphaV1(pieces2,!order),new Judge(),new Ending());
            }else if(mod == gameMod_pp){
                    setVisible(false);
                new MainWindow(new Checkerboard(img),new PeopleOne(pieces,order),new PeopleOne(pieces2,!order),new Judge(),new Ending());
            }else if(mod == gameMod_pps){
                    new ConnectWindow(this, new Checkerboard(img),new PeopleOne(pieces,order),new PeopleOne(pieces2,!order),new Judge(),new Ending());
                }
                //ResourcesPath.IMG_PATH+"/mainWindow/win10.jpg"
            System.out.println("游戏模式："+mod);
            System.out.println("棋子皮肤："+ps);
            System.out.println("棋盘皮肤："+cs);
            System.out.println("初始棋盘数量："+pc);

        });
    }
    private void textFieldInitial(){
        textField_pieceCount.setBounds(200,135+50+50+50,70,30);
        textField_pieceCount.setFont(font_textField);
    }
    private String[] getSkinNames(Map map){
        String[] names = new String[map.size()+1];
        Set set = map.keySet();
        int i = 0;
        names[i++] = "默认";
        for (Object a:set) {
            names[i++] = a+"";
        }
        return names;
    }
    private void comboBoxInitial(){
        comboBox_mode.setBounds(200,135,140,30);
        comboBox_mode.setFont(font_comboBox);
        String[] items1 = {gameMod_pp,gameMod_pc,gameMod_cc, gameMod_pps};
        ComboBoxModel<String> comboBoxModel1=new DefaultComboBoxModel(items1);
        comboBox_mode.setModel(comboBoxModel1);
        comboBox_pieceSkin.setBounds(200,135+50,140,30);
        comboBox_pieceSkin.setFont(font_comboBox);
        String[] items2 = getSkinNames(PieceConfig.getSkins());
        ComboBoxModel<String> comboBoxModel2=new DefaultComboBoxModel(items2);
        comboBox_pieceSkin.setModel(comboBoxModel2);
        comboBox_checkerboardSkin.setBounds(200,135+50+50,140,30);
        comboBox_checkerboardSkin.setFont(font_comboBox);
        String[] items3 = getSkinNames(CheckerboardConfig.getSkins());
        ComboBoxModel<String> comboBoxModel3=new DefaultComboBoxModel(items3);
        comboBox_checkerboardSkin.setModel(comboBoxModel3);
    }
    public StartWindow(){
        frameInitial();
        panelInitial();
        labelInitial();
        buttonInitial();
        textFieldInitial();
        comboBoxInitial();
    }
    private class ConnectWindow extends JFrame{
        public ConnectWindow(JFrame frame, CheckerboardSuper checkerboard, PeoplePlayer player1, PeoplePlayer player2, JudgeSuper js, IEnding ending){
            Image icon = Toolkit.getDefaultToolkit().getImage(ResourcesPath.IMG_PATH+"/startWindow/logo.jpg");
            setIconImage(icon);
            setTitle("连接设置");
            setSize(300, 200);
            setResizable(false);
            setLocationRelativeTo(null);
            setVisible(true);
            setDefaultCloseOperation(3);
            JPanel panel = new JPanel();
            JLabel label = new JLabel("IP地址");
            JLabel label2 = new JLabel();
            label2.setFont(new Font("", Font.PLAIN,20));
            label.setFont(font_label);
            String ip;
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
            TextField textField = new TextField(ip,15);
            textField.setFont(font_textField);
            Font font_button = new Font("",Font.BOLD,22);
            JButton button = new JButton("创建对局");
            button.setFont(font_button);
            button.addActionListener(e ->{
                    label2.setText("正在等待玩家连接...");
                    new Thread(() -> {
                        try {
                            ServerSocket serverSocket = new ServerSocket(8088);
                            Socket socket = serverSocket.accept();
                            //传对手Socket对象进来
                            OutputStream os = socket.getOutputStream();
                            ObjectOutputStream oos = new ObjectOutputStream(os);
                            Map<String, Object> map = new HashMap();
                            map.put("player1",player1);
                            map.put("player2",player2);
                            map.put("checkerboard",checkerboard);
                            oos.writeObject(map);
                            frame.setVisible(false);
                            setVisible(false);
                            new MainWindow(checkerboard,player1,player2,socket,js,ending);
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }).start();
            });
            JButton button2 = new JButton("连接对局");
            button2.setFont(font_button);
            button2.addActionListener(e ->{
                try {
                    //两边Player都是随机生成的，数据不同步,在一方生成把对象发过去同步
                    Socket socket = new Socket(textField.getText(),8088);
                    InputStream inputStream = socket.getInputStream();
                    ObjectInputStream ois = new ObjectInputStream(inputStream);
                    Map<String,Object> map = (Map<String,Object>)ois.readObject();
                    PeoplePlayer player1_copy = (PeoplePlayer) map.get("player1");
                    PeoplePlayer player2_copy = (PeoplePlayer) map.get("player2");
                    CheckerboardSuper checkerboard_copy = (CheckerboardSuper) map.get("checkerboard");
                    //传对手Socket对象进来
                    frame.setVisible(false);
                    setVisible(false);
                    new MainWindow(checkerboard_copy,player2_copy,player1_copy,socket,js,ending);
                } catch (IOException | ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
            });
            panel.add(label);
            panel.add(textField);
            panel.add(button);
            panel.add(button2);
            panel.add(label2);
            add(panel);

        }
    }
}
